﻿using System;
using System.Collections;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Input;
using System.Linq;
using SilverlightApplication1.ViewModels;
using SilverlightApplication1.ServiceReferenceHH;
using SilverlightApplication1.Validators;
using System.Text;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using FluentValidation;
using System.ServiceModel;


namespace SilverlightApplication1.ViewModels
{
    public class InformationViewModel : ViewModelBase
    {
        public Service1Client hhclient = new Service1Client();
        private readonly AbstractValidator<MatHang> validator = new HanghoaValidator();

       public bool flag;
        
        public InformationViewModel()
        {

            this.RefreshInformation();
            this.saveinformation = new SaveCurrentImformation(this);
             
            hhclient.insertCompleted += new EventHandler<insertCompletedEventArgs>(hhclient_insertCompleted) ;
            hhclient.deleteCompleted += new EventHandler<deleteCompletedEventArgs>(hhclient_deleteCompleted);
            hhclient.updateCompleted += new EventHandler<updateCompletedEventArgs>(hhclient_updateCompleted);
        
        }


        public void KeyDown(object sender, KeyEventArgs e)
        {

            DataGrid dg = ((DataGrid)sender);
            if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                if (e.Key == Key.D6) RefreshInformation();
                else
                    if (e.Key == Key.D1)
                    {
                        MatHang mh = new MatHang();
                        Mathangs.Insert(0, mh);
                        newinformation = Mathangs.First();
                        Currentinformation = newinformation;
                        OnPropertyChanged("Mathangs");
                    }
                    else if (e.Key == Key.D3)
                    {
                        SaveInformation.Execute("Update");
                    }
                    else if (e.Key == Key.D4)
                    {
                        SaveInformation.Execute("Delete");

                    }
                    else if (e.Key == Key.D2)
                    {
                        InsertMathang();
                    }
            }
            else { dg.BeginEdit(); }

        }
        private void hhclient_updateCompleted(object sender, updateCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.Message = "Update" + e.Result;
            }
            else
            {
                this.Message = "Update " + e.Result;
                MessageBox.Show("update");
            }
        }

        private void UpdateMathang()
        {

            refreshtioviewerrror();
            if (!this.HasErrors)
            {
                this.hhclient.updateAsync(currentinformation);
            }
        }
        private void hhclient_deleteCompleted(object sender, deleteCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.Message = "Delete " + e.Result;
            }
            else
            {
                this.Message = "Delete " + e.Result;
                mathangs.Remove(Currentinformation);
            }
        }

        private void DeleteMathang()
        {
            refreshtioviewerrror();
            if (!this.HasErrors)
            {
               hhclient.deleteAsync(currentinformation.Mahh.ToString());
            }
        }
        

        private void hhclient_insertCompleted(object sender, insertCompletedEventArgs e)
        {
            if (e.Error != null) { MessageBox.Show("Loi"); Currentinformation = Mathangs[0]; }
            else
            {
                MessageBox.Show("insert");
                this.Message = "Insert " + e.Result;
                 Mathangs.Add(e.mahh);
                Currentinformation = e.mahh;
                Mathangs[0] = new MatHang();
                OnPropertyChanged("Monhocs");
            }
        }

        private void InsertMathang()
        {
            refreshtioviewerrror();
            if (!this.HasErrors)
            {
                hhclient.insertAsync(newinformation);
            }
        }

        public void LoadingRow(Object sender, DataGridRowEventArgs e)
        {
            DataGrid dg = (DataGrid)sender;
            int index = e.Row.GetIndex();
            TextBlock cell = (TextBlock)dg.Columns[0].GetCellContent(e.Row);
            cell.Text = index + "";
        }

      
      /* public void Submit()
        {
         
            flag = true;
           
        }
        public void Submit2()
        {
          
           flag = false;
          
        }

       public void HandleKey(object sender,KeyEventArgs e)
        {
            if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                if (e.Key == Key.T && flag == true)
                {
                    //MessageBox.Show("ben trai");
                    SaveInformation.Execute("Delete");
                }
                else if ( e.Key == Key.T && flag== false)
                {
                    //MessageBox.Show("ben phai");
                    SaveInformation.Execute("Update");
                }
            }

        }
       

      /*  public RelayCommand<KeyEventArgs> KeyDown
        {
            set;
            get;
        }*/


        public void RowEditEnded(object sender, DataGridRowEditEndedEventArgs e)
        {
            DataGrid dg = (DataGrid)sender;
            int index = e.Row.GetIndex();
            string mamh = ((TextBlock)dg.Columns[1].GetCellContent(e.Row)).Text;
            if (index == 0 && mamh == "0") SaveInformation.Execute("Insert");
            else SaveInformation.Execute("Update");
        }


        private void RefreshInformation()
        {
            this.hhclient.GetAllDataCompleted += (s, e) =>
            {
                this.Mathangs = e.Result;
                OnPropertyChanged("Mathangs");
            };
            this.hhclient.GetAllDataAsync();
        }
        private SaveCurrentImformation saveinformation;
        public SaveCurrentImformation SaveInformation
        {
            get
            {
                return this.saveinformation;
                
            }   
            set
            {
                this.saveinformation = value;
                OnPropertyChanged("SaveInformation");
            }
        }



        #region data

        private MatHang newinformation = new MatHang();
        private const string tenmhproperty = "Tenmh";
        public string Tenmh
        {
            get
            {
                return this.newinformation.Tenmh;
            }
            set
            {
                this.newinformation.Tenmh = value;
                OnPropertyChanged(tenmhproperty);
                ClearError(tenmhproperty);
                var validationResult = validator.Validate(this.newinformation, tenmhproperty);
                if (!validationResult.IsValid)
                    validationResult.Errors.ToList().ForEach(x => SetError(tenmhproperty, x.ErrorMessage));
            }
        }

        private string dongiaProperty = "Dongia";
        public double? Dongia
        {
            get
            {
                return this.newinformation.Dongia;

            }
            set
            {
                this.newinformation.Dongia = value;
                OnPropertyChanged(dongiaProperty);
                ClearError(dongiaProperty);
                var validationResult = validator.Validate(this.newinformation, dongiaProperty);
                if (!validationResult.IsValid)
                    validationResult.Errors.ToList().ForEach(x => SetError(dongiaProperty, x.ErrorMessage));
            }
        }
        private const string ngaybanProperty = "Ngayban";
        public DateTime? Ngayban
        {
            get
            {
                return this.newinformation.Ngayban;
            }
            set
            {
                this.newinformation.Ngayban = value;
                OnPropertyChanged(ngaybanProperty);
                ClearError(ngaybanProperty);
                var validationResult = validator.Validate(this.newinformation, ngaybanProperty);
                if (!validationResult.IsValid)
                    validationResult.Errors.ToList().ForEach(x => SetError(ngaybanProperty, x.ErrorMessage));
            }
        }
        #endregion

        MatHang1 mh1;
        public MatHang1 Mh1
        {
            get { return mh1; }
            set {
                mh1 = value;
                OnPropertyChanged("Mh1");
 
            }
        }

        public IList<MatHang1> lstMh;
        public IList<MatHang1> LisMh
        {
            get { return lstMh; }
            set { lstMh = value; OnPropertyChanged("LstMh"); }
        }


        private IList<MatHang> mathangs;
        public IList<MatHang> Mathangs
        {
            get
            {
                return this.mathangs;
            }
            set
            {
                this.mathangs = value;
                this.OnPropertyChanged("Mathangs");
            }
        }
        private MatHang currentinformation;
        public MatHang Currentinformation
        {
            get
            {
                return this.currentinformation;
                
            }
            set
            {
                this.currentinformation = value;
                this.newinformation = this.currentinformation;
                this.OnPropertyChanged("Currentinformation");

                if (this.currentinformation == null)
                {
                    this.newinformation = new MatHang();
                }
                else
                    this.refreshtioviewerrror();
               

            }

        }

        #region
        private void update()
        {
            if (!this.HasErrors)
            {
                this.hhclient.updateCompleted += (s, e) =>
                {
                    this.Message = "Update " + e.Result.ToString();
                    //MessageBox.Show("update thanh cong");
                };
                this.hhclient.updateAsync(this.Currentinformation);
            }

        }
        private void delete()
        {
            if (!this.HasErrors)
            {
                this.hhclient.deleteCompleted += (s, e) =>
                    {
                        this.Message = "Delete" + e.Result.ToString();
                        if (e.Result)
                        {
                            this.RefreshInformation();
                        }
                    };
                this.hhclient.deleteAsync(this.currentinformation.Mahh.ToString());
            }
        }

        private void insert()
        {
            refreshtioviewerrror();
            if (!this.HasErrors)
            {
                this.hhclient.insertCompleted += (s, e) =>
                {
                    this.Message = "Insert " + e.Result.ToString();
                    if (e.Result) this.RefreshInformation();
                };
                this.hhclient.insertAsync(this.newinformation);
            }
        }
        #endregion

        private void refreshtioviewerrror()
        {
            this.Tenmh = this.newinformation.Tenmh;
            this.Dongia = this.newinformation.Dongia;
            this.Ngayban = this.newinformation.Ngayban;


        }

        private void resetdatafieds()
        {
            this.OnPropertyChanged("Currentinformation");
            this.OnPropertyChanged("Tenmh");
            this.OnPropertyChanged("Dongia");
            this.OnPropertyChanged("Ngayban");
        }





        private string message;
        public string Message
        {
            get
            {
                return this.message;
            }

            set
            {
                this.message = value;
                OnPropertyChanged("Message");
            }
        }

        #region
        public class SaveCurrentImformation : ICommand
        {

            private InformationViewModel viewmodel;
            public SaveCurrentImformation(InformationViewModel viewmodel)
            {
                this.viewmodel = viewmodel;
                this.viewmodel.PropertyChanged += (s, e) =>
                    {
                        if (this.CanExecuteChanged != null)
                        {
                            this.CanExecuteChanged(this, new EventArgs());
                        }
                    };
            }

            public bool CanExecute(object parameter)
            {
                if (parameter.ToString() == "Insert")
                    return true;
                else
                    return this.viewmodel.Currentinformation != null;
            }

            public event EventHandler CanExecuteChanged;

            public void Execute(object parameter)
            {
                switch (parameter.ToString())
                {
                    case "Update": this.viewmodel.update();
                        break;
                    case "Delete": this.viewmodel.delete();
                        break;
                    case "Insert": this.viewmodel.insert();
                        break;
                    default: break;
                }

            }


        }
        #endregion

        public class MatHang1 : ViewModelBase
        {
            //public int Mahh { get; set; }
            int mahh;


            public int mahh1
            {
                get { return mahh1; }
                set { mahh1 = value; OnPropertyChanged("mahh1"); }
            }
            string tenmh;
            public string tenmh1
            {
                get { return tenmh1; }
                set { tenmh1 = value; OnPropertyChanged("Tenmh1"); }
            }
            double? dongia;

            public double? dongia1
            {
                get { return dongia1; }
                set { dongia1 = value; OnPropertyChanged("dongia1"); }
            }
            DateTime? ngayban;
            public DateTime? ngayban1
            {
                get { return ngayban1; }
                set { ngayban1 = value; OnPropertyChanged("ngayban1"); }
            }

            public MatHang1(MatHang mh)
            {
                this.dongia1 = mh.Dongia;
                this.mahh1 = mh.Mahh;
                this.ngayban1 = mh.Ngayban;
                this.tenmh1 = mh.Tenmh;
            }


        }
    }
}
